﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using ERP.ERPSystem.ProductionSystem;
using ERP.ERPSystem.ProductionSystem.Dto;
using ERP.Team.ProductionSystem;
using Microsoft.AspNetCore.Mvc;

namespace ERP.Web.Controllers.ProductionSystem
{
    /// <summary>
    /// 生产系统-过程检验
    /// </summary>
    [Route("Process")]
    public class ProcessController : Controller
    {
        private readonly IProcessServices _processServices;
        private readonly IProductionWorkOrderMainServices _productionWorkOrderMainServices;

        // 添加工作站类
        private class WorkStation
        {
            public string WorkStationCode { get; set; }
            public string WorkStationName { get; set; }
            public string ProcessBelongs { get; set; }
            public string Workshop { get; set; }
            public string Capacity { get; set; }
        }

        public ProcessController(
            IProcessServices processServices,
            IProductionWorkOrderMainServices productionWorkOrderMainServices)
        {
            _processServices = processServices;
            _productionWorkOrderMainServices = productionWorkOrderMainServices;
        }
        
        /// <summary>
        /// 新增工序视图
        /// </summary>
        /// <returns>视图</returns>
        [HttpGet]
        public IActionResult AddProcesIndex()
        {
            return View();
        }

        /// <summary>
        /// 添加过程检验
        /// </summary>
        /// <param name="processDto"></param>
        /// <returns></returns>
        [HttpPost("Add")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddProcess([FromBody] ProcessDTO processDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new { success = false, message = "数据验证失败" });
                }

                var result = await _processServices.AddProcess(processDto);
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 显示过程检验视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetproceIndex")]
        public IActionResult GetproceIndex()
        {
            return View();
        }

        /// <summary>
        /// 显示过程检验
        /// </summary>
        /// <returns></returns>
        [Route("GetProces")]
        [HttpGet]
        public async Task<IActionResult> GetProces(int page = 1, int limit = 10, string processCode = "", 
            string processType = "", string orderCode = "", string productCode = "", 
            string productName = "", string testingResult = "")
        {
            try
            {
                var allData = await _processServices.GetProcess();
                
                // 如果没有数据，返回空结果
                if (allData == null || allData.Count == 0)
                {
                    return Json(new { 
                        success = true, 
                        data = new List<object>(), 
                        total = 0,
                        page = page,
                        limit = limit
                    });
                }
                
                // 搜索过滤
                var filteredData = allData.Where(x => 
                    (string.IsNullOrEmpty(processCode) || (x.ProcessCode != null && x.ProcessCode.Contains(processCode))) &&
                    (string.IsNullOrEmpty(processType) || (x.ProcessType != null && x.ProcessType.Contains(processType))) &&
                    (string.IsNullOrEmpty(orderCode) || (x.OrderCode != null && x.OrderCode.Contains(orderCode))) &&
                    (string.IsNullOrEmpty(productCode) || (x.ProductCode != null && x.ProductCode.Contains(productCode))) &&
                    (string.IsNullOrEmpty(productName) || (x.ProductName != null && x.ProductName.Contains(productName))) &&
                    (string.IsNullOrEmpty(testingResult) || (x.TestingResult != null && x.TestingResult.Contains(testingResult)))
                ).ToList();
                
                // 分页
                var totalRecords = filteredData.Count;
                var pagedData = filteredData.Skip((page - 1) * limit).Take(limit).ToList();
                
                return Json(new { 
                    success = true, 
                    data = pagedData, 
                    total = totalRecords,
                    page = page,
                    limit = limit
                });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message, stackTrace = ex.StackTrace });
            }
        }

        /// <summary>
        /// 根据ID获取过程检验详情
        /// </summary>
        /// <param name="id">检验单ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetProcessById/{id:int}")]
        //[Route("GetProcessById")]
        public async Task<JsonResult> GetProcessById(int id)
        {
            try
            {
                var process = await _processServices.GetProcessById(id);
                if (process == null)
                {
                    return Json(new { success = false, message = "未找到指定的过程检验记录" });
                }

                return Json(new { success = true, data = process });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 编辑过程检验视图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("Edit/{id}")]
        public async Task<IActionResult> EditProcess(int id)
        {
            try
            {
                var process = await _processServices.GetProcessById(id);
                if (process == null)
                {
                    return NotFound();
                }
                
                // 将实体转换为DTO
                var processDto = new ProcessDTO
                {
                    Id = process.Id,
                    ProcessCode = process.ProcessCode,
                    ProcessType = process.ProcessType,
                    OrderCode = process.OrderCode,
                    ProductCode = process.ProductCode,
                    ProductName = process.ProductName,
                    Specifications = process.Specifications,
                    Unitt = process.Unitt,
                    TestingNum = process.TestingNum,
                    TestingResult = process.TestingResult,
                    TestingDate = process.TestingDate,
                    TestingPerson = process.TestingPerson,
                    State = process.State
                };
                
                return View("EditProcess", processDto); // 使用专门的编辑页面
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 更新过程检验
        /// </summary>
        /// <param name="processDto"></param>
        /// <returns></returns>
        [HttpPost("Update")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UpdateProcess([FromBody] ProcessDTO processDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new { success = false, message = "数据验证失败" });
                }

                var result = await _processServices.UpdateProcess(processDto);
                if (result > 0)
                {
                    return Json(new { success = true, message = "修改成功" });
                }
                else
                {
                    return Json(new { success = false, message = "修改失败，记录不存在" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除过程检验
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("Delete")]
        public async Task<IActionResult> DeleteProcess([FromBody] List<int> ids)
        {
            try
            {
                if (ids == null || !ids.Any())
                {
                    return Json(new { success = false, message = "未选择要删除的记录" });
                }

                var result = await _processServices.DeleteProcess(ids);
                if (result)
                {
                    return Json(new { success = true, message = "删除成功" });
                }
                else
                {
                    return Json(new { success = false, message = "删除失败" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取工作站列表
        /// </summary>
        /// <param name="workStationCode">工作站编号</param>
        /// <param name="processBelongs">所属工序</param>
        /// <param name="workshop">所在车间</param>
        /// <returns></returns>
        [Route("GetWorkStationList")]
        [HttpGet]
        public async Task<JsonResult> GetWorkStationList(string workStationCode = "", string processBelongs = "", string workshop = "")
        {
            try
            {
                // 创建模拟的工作站数据
                var workStations = new List<WorkStation>
                {
                    new WorkStation { WorkStationCode = "WS0045", WorkStationName = "物料瓶上封工位", ProcessBelongs = "物料瓶上封工位", Workshop = "混装车间", Capacity = "500个/天" },
                    new WorkStation { WorkStationCode = "002", WorkStationName = "颗粒灌装工位", ProcessBelongs = "颗粒灌装工位", Workshop = "混装车间", Capacity = "2500瓶/天" },
                    new WorkStation { WorkStationCode = "003", WorkStationName = "装盖工位", ProcessBelongs = "装盖工位", Workshop = "混装车间", Capacity = "500个/天" },
                    new WorkStation { WorkStationCode = "004", WorkStationName = "检测工位", ProcessBelongs = "检测工位", Workshop = "混装车间", Capacity = "500个/天" },
                    new WorkStation { WorkStationCode = "005", WorkStationName = "贴标与包装工位", ProcessBelongs = "贴标与包装工位", Workshop = "混装车间", Capacity = "500个/天" },
                    new WorkStation { WorkStationCode = "006", WorkStationName = "合箱工位", ProcessBelongs = "合箱工位", Workshop = "混装车间", Capacity = "500个/天" },
                    new WorkStation { WorkStationCode = "WS0019", WorkStationName = "ROXYNE", ProcessBelongs = "ROXYNE", Workshop = "操作车间", Capacity = "A" },
                    new WorkStation { WorkStationCode = "WS0020", WorkStationName = "ROXYNE2", ProcessBelongs = "ROXYNE", Workshop = "操作车间", Capacity = "B" },
                    new WorkStation { WorkStationCode = "WS0021", WorkStationName = "ROXYNE3", ProcessBelongs = "ROXYNE", Workshop = "操作车间", Capacity = "C" },
                    new WorkStation { WorkStationCode = "WS0031", WorkStationName = "下料", ProcessBelongs = "焊接", Workshop = "下料", Capacity = "" }
                };

                // 应用搜索条件
                var filteredData = workStations.AsQueryable();

                if (!string.IsNullOrEmpty(workStationCode))
                {
                    filteredData = filteredData.Where(x => x.WorkStationCode.Contains(workStationCode));
                }

                if (!string.IsNullOrEmpty(processBelongs))
                {
                    filteredData = filteredData.Where(x => x.ProcessBelongs.Contains(processBelongs));
                }

                if (!string.IsNullOrEmpty(workshop))
                {
                    filteredData = filteredData.Where(x => x.Workshop.Contains(workshop));
                }

                var result = filteredData.ToList();

                return Json(new { code = 0, msg = "", count = result.Count, data = result });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, count = 0, data = new List<WorkStation>() });
            }
        }

        /// <summary>
        /// 获取生产工单列表
        /// </summary>
        /// <param name="workOrderCode">工单编码</param>
        /// <param name="workOrderName">工单名称</param>
        /// <param name="productCode">产品编号</param>
        /// <param name="productName">产品名称</param>
        /// <param name="customerName">客户名称</param>
        /// <returns></returns>
        [Route("GetProductionWorkOrderList")]
        [HttpGet]
        public async Task<JsonResult> GetProductionWorkOrderList(string workOrderCode = "", string workOrderName = "", 
            string productCode = "", string productName = "", string customerName = "")
        {
            try
            {
                // 从数据库获取生产工单数据
                var workOrders = await _productionWorkOrderMainServices.GetProductionWorkOrder(
                    workOrderCode: workOrderCode,
                    workOrderName: workOrderName,
                    productCode: productCode,
                    productName: productName,
                    customerName: customerName
                );

                return Json(new { code = 0, msg = "", count = workOrders.Count, data = workOrders });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = ex.Message, count = 0, data = new List<object>() });
            }
        }
    }
}
